/**
 * 商品分类导入
 * 商品分类指：猪肉、鸡肉、牛肉
 * 回调数据类型: [{
 *  id: number | string;
 *  name: string;
 * }]
 */
import type { FC } from 'react';
import { useState } from 'react';

import { downLoadGoods } from '@/services/coupon.service';
import { useDeepCompareEffect } from 'ahooks';
import { message, Space, Typography, Tag } from 'antd';
import styles from './index.less';
import ListLayer from './ListLayer';
import PickerModal from './PickerModal';

const { Text } = Typography;

/**
 * 商品分类导入
 */
type TProps = {
  onChange?: TAnyFunction;
  value?: any;
  left?: number;
  title: string;
  goodType: any;
};
const CommonSearchPicker: FC<TProps> = (props) => {
  const { onChange, value, left = 6, title = '商品分类', goodType } = props;
  const [visible, setVisible] = useState<boolean>(false);
  const [listVisible, setListVisible] = useState<boolean>(false);
  const [data, setData] = useState<any[]>([]);

  const handleSubmit = (val: TIdNameData[]) => {
    if (!(val && val.length)) {
      message.warn('至少选择一个选项');
    } else {
      onChange && onChange(val);
      setData(val);
      setVisible(false);
    }
  };

  useDeepCompareEffect(() => {
    if (value) {
      setData(value);
    }
  }, [value]);

  const renderText = () => (
    <div className={styles.showWrap}>
      <div className={styles.showContent}>
        <Text>
          <Text strong className="mr-16">
            {title}
          </Text>
          {data.map((o) => (
            <Tag key={o.value}>
              <span>商品ID：{o.id} </span>
              商品名称：{o.name.includes('（') ? o.name.split('（')[0] : o.name}
              {!!o?.goodsNames?.length && <span>（{o?.goodsNames?.length}个）</span>}
            </Tag>
          ))}
        </Text>
      </div>
      <Space>
        <div className={styles.showBtn} onClick={() => setListVisible(true)}>
          查看商品清单
        </div>
        <div
          className={styles.showBtn}
          onClick={async () => {
            let list: any = [];
            if (goodType === 1 || goodType === 2) {
              data.map((val) => {
                if (val.linkIds && val.linkIds.length > 0) {
                  list.push(...val.linkIds);
                }
              });
            } else {
              list = data.map((val) => val.id);
            }
            console.log('============================', list);
            try {
              const res: any = await downLoadGoods({ id: list });
              // let blob = new Blob([res], {
              //   type: 'application/vnd.ms-excel',
              // });
              // let url = window.URL.createObjectURL(blob);
              const url = window.URL.createObjectURL(res);
              const link = document.createElement('a');
              link.style.display = 'none';
              link.download = '导出清单'; // 下载的文件名称
              link.href = url;
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link);
            } catch (error) {}
          }}
        >
          导出清单
        </div>
        <div className={styles.showBtn} onClick={() => setVisible(true)}>
          编辑
        </div>
      </Space>
    </div>
  );

  return (
    <div className={styles.pickerShowContainer} style={{ paddingLeft: `${left}em` }}>
      <div className={styles.pickerShowBox}>
        {data.length > 0 ? (
          renderText()
        ) : (
          <span
            className={styles.choseBtn}
            onClick={() => {
              setVisible(true);
            }}
          >
            点击选择
          </span>
        )}
      </div>

      {visible && (
        <PickerModal
          title={title}
          goodType={goodType}
          visible={visible}
          data={data}
          onCancel={() => setVisible(false)}
          onSubmit={handleSubmit}
        />
      )}

      <ListLayer visible={listVisible} data={data} onCancel={() => setListVisible(false)} />
    </div>
  );
};

export default CommonSearchPicker;
